import request from '@/utils/request'

// 是否使用模拟数据
const USE_MOCK = true

// 模拟数据
const mockData = {
  sessions: {},
  messages: {},
  sessionIdCounter: 0,
  messageIdCounter: 0
}

// 模拟请求函数
function mockRequest(config) {
  return new Promise((resolve) => {
    setTimeout(() => {
      if (config.url.includes('/sessions') && config.method === 'post') {
        // 创建会话
        const sessionId = 'session_' + (++mockData.sessionIdCounter)
        const session = {
          ...config.data,
          sessionId: sessionId,
          id: mockData.sessionIdCounter,
          createTime: new Date(),
          updateTime: new Date(),
          status: 0,
          lastMessage: '',
          lastTime: new Date()
        }
        mockData.sessions[sessionId] = session
        resolve({
          code: 200,
          sessionId: sessionId,
          message: '会话创建成功'
        })
      } else if (config.url.includes('/sessions/') && config.method === 'get') {
        // 获取会话详情
        const sessionId = config.url.split('/').pop()
        const session = mockData.sessions[sessionId]
        if (session) {
          resolve({
            code: 200,
            data: session
          })
        } else {
          resolve({
            code: 404,
            message: '会话不存在'
          })
        }
      } else if (config.url.includes('/messages') && config.method === 'post') {
        // 发送消息
        const message = {
          ...config.data,
          id: ++mockData.messageIdCounter,
          createTime: new Date(),
          updateTime: new Date()
        }
        
        if (!mockData.messages[message.sessionId]) {
          mockData.messages[message.sessionId] = []
        }
        
        mockData.messages[message.sessionId].push(message)
        
        // 更新会话最后一条消息
        if (mockData.sessions[message.sessionId]) {
          mockData.sessions[message.sessionId].lastMessage = message.content
          mockData.sessions[message.sessionId].lastTime = new Date()
        }
        
        resolve({
          code: 200,
          message: '消息发送成功'
        })
      } else if (config.url.includes('/messages/') && config.method === 'get') {
        // 获取会话消息列表
        const sessionId = config.url.split('/').pop()
        const messages = mockData.messages[sessionId] || []
        resolve({
          code: 200,
          data: messages
        })
      } else if (config.url.includes('/messages/session/') && config.method === 'put') {
        // 批量更新会话消息状态
        const urlParts = config.url.split('/')
        const sessionId = urlParts[urlParts.length - 3]
        const status = parseInt(urlParts[urlParts.length - 1])
        
        let count = 0
        if (mockData.messages[sessionId]) {
          mockData.messages[sessionId].forEach(msg => {
            if (msg.status !== status) {
              msg.status = status
              count++
            }
          })
        }
        
        resolve({
          code: 200,
          message: `更新了${count}条消息状态`
        })
      } else if (config.url.includes('/messages/unread/') && config.method === 'get') {
        // 获取未读消息数量
        const urlParts = config.url.split('/')
        const sessionId = urlParts[urlParts.length - 2]
        const senderType = parseInt(urlParts[urlParts.length - 1])
        
        let count = 0
        if (mockData.messages[sessionId]) {
          count = mockData.messages[sessionId].filter(
            msg => msg.senderType === senderType && msg.status === 0
          ).length
        }
        
        resolve({
          code: 200,
          count: count
        })
      } else {
        // 其他请求
        resolve({
          code: 200,
          data: [],
          total: 0
        })
      }
    }, 300)
  })
}

// 根据使用模式选择适当的请求函数
const apiRequest = USE_MOCK ? mockRequest : request

// 创建会话
export function createSession(data) {
  return apiRequest({
    url: '/api/customer-service/sessions',
    method: 'post',
    data: data
  })
}

// 获取会话详情
export function getSession(sessionId) {
  return apiRequest({
    url: `/api/customer-service/sessions/${sessionId}`,
    method: 'get'
  })
}

// 获取用户会话列表
export function getUserSessions(userId) {
  return apiRequest({
    url: `/api/customer-service/sessions/user/${userId}`,
    method: 'get'
  })
}

// 获取访客会话列表
export function getVisitorSessions(visitorId) {
  return apiRequest({
    url: `/api/customer-service/sessions/visitor/${visitorId}`,
    method: 'get'
  })
}

// 获取客服会话列表
export function getServiceSessions(serviceId) {
  return apiRequest({
    url: `/api/customer-service/sessions/service/${serviceId}`,
    method: 'get'
  })
}

// 更新会话状态
export function updateSessionStatus(sessionId, status) {
  return apiRequest({
    url: `/api/customer-service/sessions/${sessionId}/status/${status}`,
    method: 'put'
  })
}

// 评价会话
export function evaluateSession(sessionId, score, content) {
  return apiRequest({
    url: `/api/customer-service/sessions/${sessionId}/evaluate`,
    method: 'put',
    params: {
      score: score,
      content: content
    }
  })
}

// 分页获取会话列表
export function getSessionList(params) {
  return apiRequest({
    url: '/api/customer-service/sessions',
    method: 'get',
    params: params
  })
}

// 发送消息
export function sendMessage(data) {
  return apiRequest({
    url: '/api/customer-service/messages',
    method: 'post',
    data: data
  })
}

// 获取会话消息列表
export function getSessionMessages(sessionId) {
  return apiRequest({
    url: `/api/customer-service/messages/${sessionId}`,
    method: 'get'
  })
}

// 更新消息状态
export function updateMessageStatus(id, status) {
  return apiRequest({
    url: `/api/customer-service/messages/${id}/status/${status}`,
    method: 'put'
  })
}

// 批量更新会话消息状态
export function updateSessionMessagesStatus(sessionId, status) {
  return apiRequest({
    url: `/api/customer-service/messages/session/${sessionId}/status/${status}`,
    method: 'put'
  })
}

// 获取未读消息数量
export function getUnreadMessageCount(sessionId, senderType) {
  return apiRequest({
    url: `/api/customer-service/messages/unread/${sessionId}/${senderType}`,
    method: 'get'
  })
} 